package com.nuo.backend.common.exception;

import com.nuo.backend.common.utils.R;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @description: TODO 处理 security 过滤器中的异常
 * @author nuo
 * @date 2022/12/17 22:39
 * @version 1.0
 */
@RestController
public class SecurityFilterExceptionHandler extends BasicErrorController {
    public SecurityFilterExceptionHandler(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        // TODO 可以通过断点调试来查看body中的信息
        Map<String, Object> body = this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        return new ResponseEntity<>(R.error(status.value(), String.valueOf(body.get("message"))), HttpStatus.OK);
    }
}
